<template>
  <div class="category-page">
    <!-- 移动端分类选择器 -->
    <div class="mobile-category-selector">
      <el-button
          class="category-selector-btn"
          @click="showCategoryDrawer = true"
      >
        <el-icon>
          <Menu/>
        </el-icon>
        <span>{{ selectedCategory ? selectedCategory.name : '选择分类' }}</span>
        <el-icon>
          <ArrowDown/>
        </el-icon>
      </el-button>
    </div>

    <!-- 分类导航 -->
    <div class="category-nav">
      <div class="nav-header">
        <h3>商品分类</h3>
      </div>

      <!-- 分类树 -->
      <div class="category-tree">
        <div
            v-for="category in categoryTree"
            :key="category.id"
            class="category-item"
        >
          <div
              :class="{ active: selectedCategoryId === category.id }"
              class="category-info"
              @click="toggleCategory(category)"
          >
            <div class="category-icon">
              <img
                  v-if="category.icon"
                  :alt="category.name"
                  :src="category.icon"
                  class="category-icon-img"
                  @error="handleImageError"
              />
              <el-icon v-else class="default-icon">
                <Box/>
              </el-icon>
            </div>
            <span class="category-name">{{ category.name }}</span>
            <el-icon
                v-if="category.children && category.children.length > 0"
                :class="{ expanded: expandedCategories.includes(category.id) }"
                class="expand-icon"
            >
              <ArrowDown/>
            </el-icon>
          </div>

          <!-- 子分类 -->
          <div
              v-if="category.children && category.children.length > 0 && expandedCategories.includes(category.id)"
              class="sub-categories"
          >
            <div
                v-for="subCategory in category.children"
                :key="subCategory.id"
                :class="{ active: selectedCategoryId === subCategory.id }"
                class="sub-category-item"
                @click="selectCategory(subCategory)"
            >
              {{ subCategory.name }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品列表区域 -->
    <div class="products-section">
      <!-- 筛选和排序 -->
      <div class="filter-bar">
        <div class="current-category">
          <span v-if="selectedCategory">{{ selectedCategory.name }}</span>
          <span v-else>全部商品</span>
        </div>

        <div class="sort-options">
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSortChange">
            <el-option label="默认排序" value="default"/>
            <el-option label="价格从低到高" value="price_asc"/>
            <el-option label="价格从高到低" value="price_desc"/>
            <el-option label="销量从高到低" value="sales_desc"/>
            <el-option label="最新上架" value="create_time_desc"/>
          </el-select>
        </div>
      </div>

      <!-- 商品网格 -->
      <div v-loading="loading" class="products-grid">
        <div
            v-for="product in products"
            :key="product.id"
            class="product-card"
            @click="goToProductDetail(product.id)"
        >
          <div class="product-image">
            <el-image
                :alt="product.name"
                :src="product.mainImage || '/placeholder.jpg'"
                fit="cover"
            />
          </div>
          <div class="product-info">
            <h4 class="product-name">{{ product.name }}</h4>
            <p class="product-subtitle">{{ product.subtitle }}</p>
            <div class="product-price">
              <span class="current-price">¥{{ product.price }}</span>
              <span v-if="product.originalPrice" class="original-price">
                ¥{{ product.originalPrice }}
              </span>
            </div>
            <div class="product-stats">
              <span class="sales">已售{{ product.sales }}件</span>
              <span class="stock">库存{{ product.stock }}件</span>
            </div>
          </div>
          <div class="product-actions">
            <el-button
                :loading="addingToCart[product.id]"
                size="small"
                type="primary"
                @click.stop="addToCart(product)"
            >
              加入购物车
            </el-button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && products.length === 0" class="empty-state">
        <el-empty description="暂无商品"/>
      </div>

      <!-- 分页 -->
      <div v-if="total > 0" class="pagination">
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[12, 24, 48]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 移动端分类抽屉 -->
    <el-drawer
        v-model="showCategoryDrawer"
        direction="ltr"
        size="280px"
        title="选择分类"
    >
      <div class="drawer-category-tree">
        <div
            v-for="category in categoryTree"
            :key="category.id"
            :class="{ active: selectedCategoryId === category.id }"
            class="drawer-category-item"
            @click="selectCategoryFromDrawer(category)"
        >
          <div class="category-info">
            <div class="category-icon">
              <img
                  v-if="category.icon"
                  :alt="category.name"
                  :src="category.icon"
                  class="category-icon-img"
                  @error="handleImageError"
              />
              <el-icon v-else class="default-icon">
                <Box/>
              </el-icon>
            </div>
            <span class="category-name">{{ category.name }}</span>
          </div>

          <!-- 子分类 -->
          <div v-if="category.children && category.children.length > 0" class="sub-categories">
            <div
                v-for="subCategory in category.children"
                :key="subCategory.id"
                :class="{ active: selectedCategoryId === subCategory.id }"
                class="sub-category-item"
                @click.stop="selectCategoryFromDrawer(subCategory)"
            >
              {{ subCategory.name }}
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {ArrowDown, Box, Menu} from '@element-plus/icons-vue'
import {getCategoryTree} from '@/api/category'
import {getProductList} from '@/api/product'
import {addToCart as addToCartApi} from '@/api/cart'
import {useCartStore, useUserStore} from '@/store'

// 路由相关
const router = useRouter()
const route = useRoute()

// 状态管理
const userStore = useUserStore()
const cartStore = useCartStore()

// 响应式数据
const loading = ref(false)
const categoryTree = ref([])
const selectedCategory = ref(null)
const selectedCategoryId = ref(null)
const products = ref([])
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const sortBy = ref('default')

// 移动端分类抽屉状态
const showCategoryDrawer = ref(false)

// 展开的分类ID列表
const expandedCategories = ref([])

// 加入购物车状态
const addingToCart = reactive({})

// 获取分类树
const fetchCategoryTree = async () => {
  try {
    const response = await getCategoryTree()
    // 后端返回的是平铺数据，需要转换为树形结构
    categoryTree.value = buildCategoryTree(response.data)

    // 分类树加载完成后，处理路由参数
    const categoryId = route.query.categoryId
    if (categoryId) {
      handleRouteChange(categoryId)
    } else {
      // 如果没有指定分类，加载所有商品
      fetchProducts()
    }
  } catch (error) {
    console.error('获取分类树失败:', error)
    ElMessage.error('获取分类失败')
  }
}

// 将平铺的分类数据转换为树形结构
const buildCategoryTree = (categories) => {
  const categoryMap = new Map()
  const rootCategories = []

  // 先创建所有分类的映射
  categories.forEach(category => {
    categoryMap.set(category.id, {
      ...category,
      children: []
    })
  })

  // 构建树形结构
  categories.forEach(category => {
    if (category.parentId === 0) {
      // 一级分类
      rootCategories.push(categoryMap.get(category.id))
    } else {
      // 子分类
      const parent = categoryMap.get(category.parentId)
      if (parent) {
        parent.children.push(categoryMap.get(category.id))
      }
    }
  })

  return rootCategories
}

// 选择分类
const selectCategory = (category) => {
  selectedCategory.value = category
  selectedCategoryId.value = category.id
  currentPage.value = 1

  // 统一使用fetchProducts，根据分类层级决定是否包含子分类
  fetchProducts()

  // 更新URL查询参数
  router.replace({
    path: '/category',
    query: {categoryId: category.id}
  })
}


// 获取商品列表
const fetchProducts = async () => {
  try {
    loading.value = true

    let response
    if (selectedCategoryId.value) {
      // 构建查询参数
      const params = {
        categoryId: selectedCategoryId.value,
        current: currentPage.value,
        size: pageSize.value,
        sortBy: getSortField(),
        sortOrder: getSortOrder()
      }

      // 如果是一级分类，包含子分类商品
      if (selectedCategory.value && selectedCategory.value.level === 1) {
        params.includeSubCategories = true
      }

      // 使用通用商品列表API
      response = await getProductList(params)
    } else {
      // 获取所有商品
      response = await getProductList({
        current: currentPage.value,
        size: pageSize.value,
        sortBy: getSortField(),
        sortOrder: getSortOrder()
      })
    }

    products.value = response.data.records || []
    total.value = response.data.total || 0
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品失败')
  } finally {
    loading.value = false
  }
}

// 获取排序字段
const getSortField = () => {
  switch (sortBy.value) {
    case 'price_asc':
    case 'price_desc':
      return 'price'
    case 'sales_desc':
      return 'sales'
    case 'create_time_desc':
      return 'create_time'
    default:
      return 'sort_order'
  }
}

// 获取排序方向
const getSortOrder = () => {
  switch (sortBy.value) {
    case 'price_desc':
    case 'sales_desc':
    case 'create_time_desc':
      return 'desc'
    default:
      return 'asc'
  }
}

// 处理排序变化
const handleSortChange = () => {
  currentPage.value = 1
  fetchProducts()
}

// 处理页面大小变化
const handleSizeChange = () => {
  currentPage.value = 1
  fetchProducts()
}

// 处理当前页变化
const handleCurrentChange = () => {
  fetchProducts()
}

// 加入购物车
const addToCart = async (product) => {
  if (!userStore.isLoggedIn()) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    addingToCart[product.id] = true

    await addToCartApi({
      productId: product.id,
      quantity: 1
    })

    ElMessage.success('已加入购物车')
    // 更新购物车统计
    await cartStore.fetchCartSummary()
  } catch (error) {
    console.error('加入购物车失败:', error)
    ElMessage.error('加入购物车失败')
  } finally {
    addingToCart[product.id] = false
  }
}

// 跳转到商品详情
const goToProductDetail = (productId) => {
  router.push(`/product/${productId}`)
}

// 处理图片加载错误
const handleImageError = (event) => {
  // 图片加载失败时隐藏图片，显示默认图标
  event.target.style.display = 'none'
  const parentElement = event.target.parentElement
  const defaultIcon = parentElement.querySelector('.default-icon')
  if (defaultIcon) {
    defaultIcon.style.display = 'block'
  }
}

// 切换分类展开状态
const toggleCategory = (category) => {
  if (category.children && category.children.length > 0) {
    const index = expandedCategories.value.indexOf(category.id)
    if (index > -1) {
      expandedCategories.value.splice(index, 1)
    } else {
      expandedCategories.value.push(category.id)
    }
  } else {
    // 如果没有子分类，直接选择该分类
    selectCategory(category)
  }
}

// 从抽屉选择分类
const selectCategoryFromDrawer = (category) => {
  selectCategory(category)
  showCategoryDrawer.value = false
}

// 从分类树中查找分类的辅助函数
const findCategory = (categories, id) => {
  for (const category of categories) {
    if (category.id === id) {
      return category
    }
    if (category.children) {
      const found = findCategory(category.children, id)
      if (found) return found
    }
  }
  return null
}

// 处理路由参数变化
const handleRouteChange = (categoryId) => {
  if (categoryId && categoryTree.value.length > 0) {
    selectedCategoryId.value = parseInt(categoryId)
    selectedCategory.value = findCategory(categoryTree.value, parseInt(categoryId))
    currentPage.value = 1
    fetchProducts()
  } else if (!categoryId) {
    selectedCategory.value = null
    selectedCategoryId.value = null
    currentPage.value = 1
    fetchProducts()
  }
}

// 监听路由查询参数变化
watch(
    () => route.query.categoryId,
    handleRouteChange
)

// 组件挂载时获取数据
onMounted(() => {
  fetchCategoryTree()
})
</script>

<style scoped>
.category-page {
  display: flex;
  min-height: 100vh;
  background: #f5f5f5;
}

/* 移动端分类选择器 */
.mobile-category-selector {
  display: none;
  padding: 15px;
  background: white;
  border-bottom: 1px solid #f0f0f0;
}

.category-selector-btn {
  width: 100%;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  color: #495057;
  font-size: 14px;
}

.category-selector-btn:hover {
  background: #e9ecef;
  border-color: #409eff;
}

/* 分类导航 */
.category-nav {
  width: 250px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow-y: auto;
  border: 1px solid #f0f0f0;
}

.nav-header {
  padding: 24px 20px;
  border-bottom: 2px solid #f0f0f0;
  background: linear-gradient(135deg, #f8f9fa, #ffffff);
}

.nav-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  text-align: center;
}

.category-tree {
  padding: 8px 0;
}

.category-item {
  cursor: pointer;
  border-bottom: 1px solid #f8f9fa;
  position: relative;
}

.category-item.active > .category-info {
  background: var(--primary-50);
  color: var(--primary-color);
  font-weight: 600;
  border-left: 4px solid var(--primary-color);
}

.category-item.active::before {
  content: '';
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 0;
  height: 0;
  border-left: 8px solid #409eff;
  border-top: 6px solid transparent;
  border-bottom: 6px solid transparent;
}

.category-info {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  transition: all 0.3s ease;
  position: relative;
  cursor: pointer;
}

.category-info:hover {
  background: var(--primary-50);
  transform: translateX(4px);
}

.expand-icon {
  margin-left: auto;
  transition: transform 0.3s ease;
  color: var(--text-tertiary);
}

.expand-icon.expanded {
  transform: rotate(180deg);
}

.category-icon {
  margin-right: 10px;
  color: #409eff;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.category-icon-img {
  width: 20px;
  height: 20px;
  object-fit: cover;
  border-radius: 2px;
}

.default-icon {
  display: none;
}

.category-name {
  font-size: 14px;
  font-weight: 500;
}

.sub-categories {
  background: #fafafa;
  padding: 5px 0;
}

.sub-category-item {
  padding: 8px 20px 8px 50px;
  font-size: 13px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
}

.sub-category-item:hover,
.sub-category-item.active {
  background: #e3f2fd;
  color: #409eff;
}

/* 商品列表区域 */
.products-section {
  flex: 1;
  padding: 20px;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.current-category {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  position: relative;
  padding-left: 20px;
}

.current-category::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #409eff, #67c23a);
  border-radius: 2px;
}

.sort-options .el-select {
  width: 160px;
}

/* 商品网格 */
.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.product-card {
  background: var(--bg-card);
  border-radius: var(--radius-2xl);
  overflow: hidden;
  box-shadow: var(--shadow-md);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid var(--border-light);
  position: relative;
}

.product-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: var(--gradient-primary);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.product-card:hover {
  transform: translateY(-6px);
  box-shadow: var(--shadow-xl);
  border-color: var(--primary-color);
}

.product-card:hover::before {
  opacity: 1;
}

.product-image {
  width: 100%;
  height: 160px;
  overflow: hidden;
}

.product-image .el-image {
  width: 100%;
  height: 100%;
}

.product-info {
  padding: 12px;
}

.product-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-subtitle {
  font-size: 12px;
  color: #909399;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-price {
  margin-bottom: 8px;
}

.current-price {
  font-size: 1.125rem;
  font-weight: 700;
  color: var(--primary-color);
}

.original-price {
  font-size: 0.875rem;
  color: var(--text-tertiary);
  text-decoration: line-through;
  margin-left: 0.5rem;
}

.product-stats {
  font-size: 12px;
  color: #909399;
  display: flex;
  justify-content: space-between;
}

.product-actions {
  padding: 0 12px 12px;
}

.product-actions .el-button {
  width: 100%;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
}

/* 响应式设计 */
/* 平板端 */
@media (max-width: 1024px) {
  .category-nav {
    width: 220px;
  }

  .products-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
  }
}

/* 抽屉样式 */
.drawer-category-tree {
  padding: 0;
}

.drawer-category-item {
  cursor: pointer;
  border-bottom: 1px solid #f8f9fa;
  position: relative;
}

.drawer-category-item.active > .category-info {
  background: var(--primary-50);
  color: var(--primary-color);
  font-weight: 600;
  border-left: 4px solid var(--primary-color);
}

.drawer-category-item .category-info {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  transition: all 0.3s ease;
}

.drawer-category-item .category-info:hover {
  background: #f8f9fa;
}

.drawer-category-item .category-icon {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: var(--primary-color);
}

.drawer-category-item .category-icon-img {
  width: 16px;
  height: 16px;
  object-fit: cover;
  border-radius: 2px;
}

.drawer-category-item .category-name {
  font-size: 14px;
  color: #303133;
}

.sub-categories {
  background: #f8f9fa;
  padding: 8px 0;
}

.sub-category-item {
  padding: 8px 20px 8px 52px;
  font-size: 13px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s ease;
}

.sub-category-item:hover {
  background: var(--primary-100);
  color: var(--primary-color);
}

.sub-category-item.active {
  background: var(--primary-200);
  color: var(--primary-dark);
  font-weight: 600;
}

/* 移动端 */
@media (max-width: 768px) {
  .mobile-category-selector {
    display: block;
    margin-bottom: 1rem;
  }

  .category-nav {
    display: none;
  }

  .category-page {
    flex-direction: column;
    padding: 1rem;
  }

  .products-section {
    padding: 0;
    margin-top: 0;
  }

  .filter-bar {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
    padding: 1rem 1.5rem;
    margin-bottom: 1rem;
  }

  .current-category {
    font-size: 1rem;
    font-weight: 600;
  }

  .sort-options .el-select {
    width: 100%;
  }

  .products-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 1rem;
    padding: 0 1rem;
  }

  .product-image {
    height: 140px;
  }

  .product-info {
    padding: 1rem;
  }

  .product-name {
    font-size: 0.875rem;
    line-height: 1.3;
    margin-bottom: 0.5rem;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .product-price {
    margin-bottom: 0.5rem;
  }

  .current-price {
    font-size: 1rem;
  }

  .original-price {
    font-size: 0.75rem;
  }

  .product-stats {
    font-size: 11px;
  }

  .category-icon {
    width: 20px;
    height: 20px;
  }

  .category-icon-img {
    width: 16px;
    height: 16px;
  }

  .pagination {
    padding: 10px;
  }
}

/* 小屏手机 */
@media (max-width: 480px) {
  .products-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }

  .product-card {
    padding: 6px;
  }

  .product-image {
    height: 100px;
  }

  .product-name {
    font-size: 12px;
  }

  .current-price {
    font-size: 13px;
  }

  .original-price {
    font-size: 10px;
  }

  .product-stats {
    font-size: 10px;
  }

  .category-nav {
    max-height: 150px;
  }

  .nav-header {
    padding: 12px;
    font-size: 14px;
  }

  .category-info {
    padding: 10px 12px;
  }

  .category-name {
    font-size: 13px;
  }

  .sub-category-item {
    padding: 6px 12px 6px 32px;
    font-size: 12px;
  }

  .filter-bar {
    padding: 8px 12px;
  }

  .current-category {
    font-size: 13px;
  }
}

/* 超小屏 */
@media (max-width: 360px) {
  .products-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }

  .product-card {
    display: flex;
    padding: 8px;
  }

  .product-image {
    width: 80px;
    height: 80px;
    margin-right: 10px;
    flex-shrink: 0;
  }

  .product-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .product-name {
    font-size: 12px;
    margin-bottom: 5px;
  }

  .product-price {
    margin-bottom: 5px;
  }

  .product-actions {
    padding: 0;
  }

  .product-actions .el-button {
    height: 28px;
    font-size: 12px;
  }
}
</style>
